package org.example.myleet.p946;

import java.util.Deque;
import java.util.LinkedList;

public class Solution {
    public boolean validateStackSequences(int[] pushed, int[] popped) {
        int i = 0, j = 0;
        Deque<Integer> stack = new LinkedList<>();
        while (i < pushed.length || j < popped.length) {
            if (stack.isEmpty()) {
                stack.push(pushed[i++]);
            } else if (stack.peek() == popped[j]) {
                stack.pop();
                ++j;
            } else if (i < pushed.length) {
                stack.push(pushed[i++]);
            } else {
                return false;
            }
        }
        return stack.isEmpty();
    }
}
